package com.parktech.sun.web.controller.management.specialtopic;

import com.parktech.sun.domain.model.Constants;
import com.parktech.sun.domain.model.specialtopic.SpecialTopic;
import com.parktech.sun.domain.model.specialtopic.SpecialTopicAttachment;
import com.parktech.sun.domain.model.specialtopic.SpecialTopicCategory;
import com.parktech.sun.domain.repository.Page;
import com.parktech.sun.domain.service.specialtopic.SpecialTopicService;
import com.parktech.sun.utils.FileHelper;
import com.parktech.sun.utils.ImageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * User: Think
 * Date: 11-1-12
 * Time: 下午7:58
 */
@Controller
@RequestMapping("/management/specialtopics")
public class SpecialTopicController {

    private int pageSize = Constants.PAGINATION_PAGE_SIZE;

    private SpecialTopicService specialTopicService;

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    @Autowired
    public SpecialTopicController(SpecialTopicService specialTopicService) {
        this.specialTopicService = specialTopicService;
    }

    @RequestMapping(value = "/search", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView search(@ModelAttribute SpecialTopicSearchForm specialTopicSearchForm) {

        Page page = new Page(pageSize, specialTopicSearchForm.getPageNo());

        ModelAndView modelAndView = new ModelAndView("management/specialtopic/specialTopicSearch");

        return modelAndView.addObject(
                specialTopicService.search(
                        specialTopicSearchForm.getTitle(), specialTopicSearchForm.getCategory(), specialTopicSearchForm.getPublishStatus(), page));
    }

    @RequestMapping(value = "/search", method = RequestMethod.DELETE)
    public String delete(@RequestParam("specialTopicIds") Long[] specialTopicIds) {
        specialTopicService.deleteAll(specialTopicIds);
        return "redirect:search";
    }

    @ModelAttribute("allCategories")
    public List<SpecialTopicCategory> populateAllCategories() {
        return specialTopicService.searchCategory(null, new Page(1000, 1)).getResult();
    }

    @ModelAttribute("allPositions")
    public Map<Integer, String> populateAllPositions() {
        Map<Integer, String> allCategories = new TreeMap<Integer, String>();
        allCategories.put(1, "图片新闻");
        allCategories.put(2, "置顶新闻");
        allCategories.put(3, "普通显示");
        return allCategories;
    }

    @ModelAttribute("specialTopic")
    public SpecialTopic populateModel(HttpServletRequest request) {
        String strId = request.getParameter("id");

        if (strId == null || strId.equals("-1")) {
            return new SpecialTopic();
        }
        return specialTopicService.getById(new Long(strId));
    }

    @ModelAttribute("allPublishStatus")
    public Map<Integer, String> populateAllPublishStatus() {
        Map<Integer, String> allPublishStatus = new HashMap<Integer, String>();
//        allPublishStatus.put(-1, "所有");
        allPublishStatus.put(0, "未发布");
        allPublishStatus.put(1, "已发布");
        return allPublishStatus;
    }

    @RequestMapping(value = "/{specialTopicId}", method = RequestMethod.GET)
    public String edit(@PathVariable Long specialTopicId, Model model) {
        SpecialTopic specialTopic = specialTopicService.getById(specialTopicId);
        model.addAttribute(specialTopic);
        return "management/specialtopic/specialTopicForm";
    }

    @RequestMapping(method = RequestMethod.GET)
    public String create(Model model) {
        model.addAttribute(new SpecialTopic());
        return "management/specialtopic/specialTopicForm";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String save(@ModelAttribute @Valid SpecialTopic specialTopic, BindingResult result,
                       @RequestParam("attachments") MultipartFile[] attachments,
                       @RequestParam("image") MultipartFile image,
                       @RequestParam("delAttachmentIds") Long[] delAttachmentIds, HttpServletRequest request)
            throws IOException {

        if (result.hasErrors()) {
            return "management/specialtopic/specialTopicForm";
        }
        specialTopicService.clearThenSaveOrUpdateBean(specialTopic);

        if (delAttachmentIds != null) {
            deleteAttachments(specialTopic, delAttachmentIds, request.getSession().getServletContext());
        }

        if (image != null && !image.isEmpty()) {
            processImage(specialTopic, image, request.getSession().getServletContext());
        }

        if (attachments.length > 0) {
            processAttachments(specialTopic, attachments, request.getSession().getServletContext());
        }
        specialTopicService.saveOrUpdateBean(specialTopic);

        return "redirect:/management/specialtopics/search";
    }

    private void processImage(SpecialTopic specialTopic, MultipartFile image, ServletContext servletContext) throws IOException {

        String specialTopicPath = servletContext.getRealPath("/upload/specialTopic/" + specialTopic.getId());
        File specialTopicDir = new File(specialTopicPath);
        if (!specialTopicDir.exists()) specialTopicDir.mkdirs();

        File imageFile = new File(specialTopicDir, image.getOriginalFilename());
        if (imageFile.exists()) {
            imageFile.delete();
        }
        FileHelper.saveFile(image.getInputStream(), imageFile);
        specialTopic.setImageName(image.getOriginalFilename());
    }

    private void deleteAttachments(SpecialTopic specialTopic, Long[] delAttachmentIds, ServletContext servletContext) {
        List<SpecialTopicAttachment> attachmentList = specialTopic.getAttachmentList();
        if (attachmentList == null) {
            return;
        }
        String specialTopicPath = servletContext.getRealPath("/upload/specialTopic/" + specialTopic.getId());
        File specialTopicDir = new File(specialTopicPath);
        if (!specialTopicDir.exists()) specialTopicDir.mkdirs();

        for (Iterator<SpecialTopicAttachment> iterator = attachmentList.iterator(); iterator.hasNext();) {
            SpecialTopicAttachment attachment = iterator.next();
            for (Long delAttachmentId : delAttachmentIds) {
                if (attachment.getId().equals(delAttachmentId)) {
                    iterator.remove();
                    attachmentList.remove(attachment);
                    attachment.setSpecialTopic(null);
                    File toDelFile = new File(specialTopicDir, attachment.getName());
                    if (toDelFile.exists()) toDelFile.delete();
                }
            }
        }
    }

    private void processAttachments(SpecialTopic specialTopic, MultipartFile[] attachments, ServletContext servletContext) throws IOException {

        String specialTopicPath = servletContext.getRealPath("/upload/specialTopic/" + specialTopic.getId());
        File specialTopicDir = new File(specialTopicPath);
        if (!specialTopicDir.exists()) specialTopicDir.mkdirs();

        List<SpecialTopicAttachment> attachmentList = specialTopic.getAttachmentList();
        if (attachmentList == null) {
            attachmentList = new ArrayList<SpecialTopicAttachment>();
            specialTopic.setAttachmentList(attachmentList);
        }
        for (MultipartFile attachment : attachments) {
            if (attachment == null || attachment.isEmpty()) {
                continue;
            }
            String originalFilename = attachment.getOriginalFilename();
            File target = new File(specialTopicDir, attachment.getOriginalFilename());
            if (target.exists()) {
                target.delete();
            } else {
                attachmentList.add(new SpecialTopicAttachment(originalFilename, specialTopic));
            }

            FileHelper.saveFile(attachment.getInputStream(), target);
        }
    }

}
